package org.alfresco.demo.rfernandes.cmdlineaction;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

public class CommandExecutor {

	private static Logger logger = Logger.getLogger(CommandExecutor.class);

	private class StreamGobbler extends Thread {
		InputStream is;
		String type;

		public StreamGobbler(InputStream is, String type) {
			this.is = is;
			this.type = type;
		}

		public void run() {
			try {
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				String content = "";
				while ((line = br.readLine()) != null)
					content += type + ">" + line;
				if(!content.trim().equals(""))
					logger.info(content);
			} catch (IOException ioe) {
				logger.fatal(ioe);
			}
		}
	}

	public void execute(String command) {

		try {

			Runtime rt = Runtime.getRuntime();
			logger.info("Executing: " + command);
			Process proc = rt.exec(command);
			// any error message?
			StreamGobbler errorGobbler = new StreamGobbler(
					proc.getErrorStream(), "ERROR");

			// any output?
			StreamGobbler outputGobbler = new StreamGobbler(
					proc.getInputStream(), "OUTPUT");

			// kick them off
			errorGobbler.start();
			outputGobbler.start();

			// any error???
			int exitVal = proc.waitFor();
			logger.info("ExitValue: " + exitVal);
		} catch (Throwable e) {
			logger.fatal(e);
		}
	}
}
